package ps.client.gui.util;

import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Toolkit;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.prefs.Preferences;

import javax.swing.JWindow;

@SuppressWarnings("serial")
public class PrefWindow extends JWindow {
	
	protected static final String WINDOW_LOCATION_X = "WindowLocationX";
	protected static final String WINDOW_LOCATION_Y = "WindowLocationY";
	protected static final String WINDOW_WIDTH = "WindowWidth";
	protected static final String WINDOW_HEIGHT = "WindowHeight";
	protected static final String WINDOW_IS_VISIBLE = "WindowIsVisible";
	
	private static int windowCount = 0;
	private static int NO_VALUE = Integer.MIN_VALUE;

	Preferences prefNode;
	
	WindowAdapter windowAdapter = new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
            saveSettings();
        }
    };
    
    protected PrefWindow(Frame owner, String prefNodeName) {
		super(owner);
		prefNode = Preferences.userRoot().node(prefNodeName);
		addWindowListener(windowAdapter);
		windowCount++;
		loadSettings();
	}
	
	public Preferences getPrefNode() {
		return prefNode;
	}
	
	protected void loadSettings() {
    	setSize(prefNode.getInt(WINDOW_WIDTH, getWidth() > 0 ? getWidth() : 650), prefNode.getInt(WINDOW_HEIGHT, getHeight() > 0 ? getHeight() : 400));

    	int posX = prefNode.getInt(WINDOW_LOCATION_X, getLocation().x > 0 ? getLocation().x : NO_VALUE);
        int posY = prefNode.getInt(WINDOW_LOCATION_Y, getLocation().y > 0 ? getLocation().y : NO_VALUE);
        if (posX > NO_VALUE && posY > NO_VALUE) {
            setLocation(posX, posY);
        } else {
            centerFrameOnScreen();
        }
	}
	
	public void saveSettings() {
		prefNode.putInt(WINDOW_LOCATION_X, getLocation().x);
		prefNode.putInt(WINDOW_LOCATION_Y, getLocation().y);
		prefNode.putInt(WINDOW_WIDTH, getSize().width);
		prefNode.putInt(WINDOW_HEIGHT, getSize().height);
		prefNode.putBoolean(WINDOW_IS_VISIBLE, isVisible());
	}
	
	protected void centerFrameOnScreen() {
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        Dimension frameSize = getSize();
        if (frameSize.height > screenSize.height) {
            frameSize.height = screenSize.height - 100;
        }
        if (frameSize.width > screenSize.width) {
            frameSize.width = screenSize.width - 100;
        }
        setLocation((screenSize.width - frameSize.width) / 2,
                (screenSize.height - frameSize.height) / 2);
    }
	
	protected void clean() {
		removeWindowListener(windowAdapter);
	}
	
	public void setVisibility() {
        setVisible(prefNode.getBoolean(WINDOW_IS_VISIBLE, false));
    }
	
	@Override
	public void setVisible(boolean b) {
		super.setVisible(b);
	}

    public static int getWindowCount() {
        return windowCount;
    }
}
